import { error, log, Ora } from '@/util';
import { ClonePath } from '@/constant';
import { basePreSolve, removeOldVersion } from './generate';
import { ICombinedJSON } from '@/types';
import { removeFile } from '@/util/files';
import { ProjectRoot, Options } from '@/constant';
import { check } from '../check';
const download = require('download-git-repo');


function generate(option: string) {
    const savePath = ProjectRoot[option];
    const repoPath = `direct:${ClonePath[option]}`;

    try {
        removeOldVersion(savePath);
    } catch(e) {
        error('remove old version of template faild...');
    }

    let ora = Ora(`clone ${option}...`);
    
    ora.start();
    /** clone 模板并根据配置进行修改 */
    download(repoPath, savePath, { clone: true }, (err: string) => {
            if (err) {
                error((err as string).toString());
                ora.fail();
            }
            else {
                ora.succeed();
                ora = Ora('solve relative documents');
                ora.start();
                try {
                    // 脱敏或其它处理
                    switch(option) {
                        case Options.Node:
                            const combinedJSON = check();
                            basePreSolve(combinedJSON);
                            break;
                        case Options.React:
                        case Options.Cli:
                        case Options.Package:
                        case Options.Electron:
                            break;
                        default:
                            break;
                    }
                    ora.succeed();
                    log(`Required documents all settled at: ${ProjectRoot[option]}.`);
                } catch(e) {
                    error((e as string).toString());
                    ora.fail();
                    removeFile(savePath);
                }
            }
        }
    )
}

export {
    generate,
}